import { cardType } from "./card";

// 流式输出
export const flow = (response: any, newContent: any, answers: any) => {
  const uint8Array = new Uint8Array(response.data);
  let text = String.fromCharCode.apply(null, uint8Array);
  let lines = decodeURIComponent(escape(text)).split('\n');
  let stop = false

  lines.forEach((line: string) => {
    if (line.startsWith("data: ")) {
      line = line.substring(6);
    } else {
      return false;
    }

    let data: any
    try {
      data = JSON.parse(line);
    } catch (error) {
      return false;
    }

    if (data.choices[0].finish_reason === "stop") {
      stop = true
      return false;
    }

    if (data.choices) {
      let content
      try{
        content = data.choices[0].delta.content;
      } catch {
        return false
      }
    
      if (content) {
        newContent += content
        let markdownContent = markdown(newContent)

        const cardTypePattern = /"cardType"\s*:\s*"([^"]+)"/;
        const match = newContent.match(cardTypePattern);
        let type
        if(match && match[1]){
          type = cardType[match[1]]
        }

        answers[answers.length - 1].content = markdownContent
        answers[answers.length - 1].newContent = newContent
        if(type){
          answers[answers.length - 1].type = type
        }
      }
    }
  });

  let result = {
    newContent: newContent,
    answers: answers,
    stop
  };
  return result;
};

// markdown解析
const markdown = (content: string) => {
  let towxml = require('../towxml/index')
  let result = towxml(content, 'markdown')
  return result
}